import QDRANT from './QDRANT.js';
import { jinaQuery } from './jina.js';
import vbD from '@3-/vb/vbD.js';
import {QDRANT_COLLECTION_NAME} from './conf.js';

// 搜索服务实现
export default async (call, callback) => {
  const { query, repo_id_list, user_id_list, limit, offset } = call.request;
  const queryVector = await jinaQuery(query);

  // 构建过滤条件
  const must = [];

  if (repo_id_list && repo_id_list.length > 0) {
    must.push({
      key: "repo_id",
      match: { any: repo_id_list },
    });
  }

  if (user_id_list && user_id_list.length > 0) {
    must.push({
      key: "user_id",
      match: { any: user_id_list },
    });
  }
  const option = {
    vector: queryVector,
    limit: limit || 20,
    offset,
    with_payload: true, // 获取 payload 数据
  };
    
  if(must.length > 0){
    option.filter = {
      must
    }
  }

  const li = [];

  for(const i of await QDRANT.search(QDRANT_COLLECTION_NAME, option)){
    const bin = Buffer.allocUnsafe(6);
    bin.writeUIntBE(i.id, 0, 6 );
    let count = 0;
    for(const j of bin){
      if(j != 0){
        break
      }
      ++count
    }
    const [id, pos] = vbD(bin.slice(count));
    li.push({id,pos,score:i.score})
  }
  
  // TODO: 需要对结果进行去重，返回完整的文章

  callback(null, { li });
}

